import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateSupplierDto } from './dto/create-supplier.dto';
import { Supplier } from './entities/supplier.entity';
import { GoodsCategory } from '../goods-category/entities/goods-category.entity';
import { Not, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { dateNo } from 'src/utils/fun';
import { Admin } from 'src/admin/entities/admin.entity';
@Injectable()
export class SupplierService {
  constructor(
    @InjectRepository(Supplier)
    private readonly supplierRepository: Repository<Supplier>,
    ) {}
  async isSupplierExists(where){
    const result = await this.supplierRepository.findOne({where});
    return !!result
  }
  async create(createSupplierDto: CreateSupplierDto, tokenInfo) {
    try{
      let where = {}
      if(createSupplierDto.id){
        where = {id: Not(createSupplierDto.id)}
      }
      //验证名称重复
      const isNameExists = await this.isSupplierExists({
        ...where,
        name: createSupplierDto.name,
      })
      if(isNameExists){
        throw new HttpException('供应商名称不可重复', HttpStatus.INTERNAL_SERVER_ERROR);
      }
      //保存
      
      const saveData = {
        ...createSupplierDto,
        createAdminId: tokenInfo.id,
        categoryIds: createSupplierDto.categoryIds && createSupplierDto.categoryIds.length > 0 ? ',' + createSupplierDto.categoryIds.join(',') + ',' : ''
      }
      // 如果 createSupplierDto.id 不为真（即新增操作），则添加 number 字段
      if (!createSupplierDto.id) {
        saveData['code'] = 'GYS' + dateNo() + Math.floor(Math.random() * 100).toString().padStart(3, '0')
      }
      //return
      const savedSupplier = await this.supplierRepository.save(saveData)
      return savedSupplier
    } catch (error) {
      throw new HttpException(error.message, error.status, {
        cause: error
      });
    }
  }

  async findAll(query) {
    try {
      const { page = 1, limit = 20, keyName = ''} = query
      const queryBuilder = await this.supplierRepository
      .createQueryBuilder('supplier')
      .leftJoinAndSelect(Admin, 'admin', 'admin.id = supplier.createAdminId')
      .leftJoinAndSelect(GoodsCategory, 'category', `FIND_IN_SET(category.id, supplier.categoryIds) > 0`)
      .select([
        'supplier.id AS id',
        'supplier.name AS name',
        'supplier.code AS code',
        'supplier.contacts AS contacts',
        'supplier.mobile AS mobile',
        'supplier.email AS email',
        'supplier.categoryIds AS categoryIds',
        'supplier.address AS address',
        'supplier.creditCode AS creditCode',
        'supplier.tin AS tin',
        'supplier.bank AS bank',
        'supplier.account AS account',
        'supplier.bankNo AS bankNo',
        'supplier.remark AS remark',
        'supplier.createTime AS createTime',
        'GROUP_CONCAT(category.name) AS categoryNames',
        'admin.nickname AS createAdminName',
      ])
      .groupBy('supplier.id')
      
      // 添加 categoryId 等值查询条件
      // if (categoryId) {
      //   queryBuilder.andWhere('goods.categoryId = :categoryId', { categoryId });
      // }

      // if (number) {
      //   queryBuilder.andWhere('goods.number = :number', { number });
      // }
      
      // 添加 keyName 对 name 字段的模糊查询条件
      if (keyName) {
        queryBuilder.andWhere('supplier.name LIKE :keyName OR supplier.code LIKE :keyName', { keyName: `%${keyName}%` });
      }
      const supplier = await queryBuilder
        .offset(Number((page - 1) * limit))
        .limit(Number(limit))
        .getRawMany();
      const total = await queryBuilder
        .getCount();
      return [
        supplier, total
      ]
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async findAllBySelect(query) {
    try {
      const { keyName = ''} = query
      const queryBuilder = await this.supplierRepository
      .createQueryBuilder('supplier')
      .select([
        'supplier.id AS id',
        'supplier.name AS name',
        'supplier.code AS code',
      ])
      // 添加 keyName 对 name 字段的模糊查询条件
      if (keyName) {
        queryBuilder.andWhere('supplier.name LIKE :keyName OR supplier.code LIKE :keyName', { keyName: `%${keyName}%` });
      }
      const supplier = await queryBuilder
        .getRawMany();
      return supplier
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} supplier`;
  }

  async delete(id: string) {
    try {
      return await this.supplierRepository.delete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async remove(id: string) {
    try {
      return await this.supplierRepository.softDelete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
